package com.quanyan.club.service.impl;

import baidu.webapi.impl.BaiduLBS;
import baidu.webapi.model.AddressComponent;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.constants.ClubMemberPriorityConstants;
import com.quanyan.club.entity.RespClubBaseInfo;
import com.quanyan.club.entity.RespClubXpLevelMsg;
import com.quanyan.club.entity.RespShareUrl;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.ReqClub;
import com.quanyan.club.entity.vo.req.ReqClubPage;
import com.quanyan.club.entity.vo.req.ReqClubRecommend;
import com.quanyan.club.entity.vo.req.ReqClubSearch;
import com.quanyan.club.entity.vo.resp.*;
import com.quanyan.club.entity.vo.resp.movement.RespClubIntegralRank;
import com.quanyan.club.mapper.*;
import com.quanyan.club.mq.producer.ClubXpLevelProducer;
import com.quanyan.club.pullclub.service.PullClubSupportService;
import com.quanyan.club.service.*;
import com.quanyan.club.thread.ClubSolrIndexThread;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.encrypt.Coder;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.*;
import com.quanyan.common.vo.resp.RespCity;
import com.quanyan.common.vo.resp.RespDistrict;
import com.quanyan.im.entity.req.ModifyIMGroup;
import com.quanyan.im.entity.req.ReqCreateIMGroup;
import com.quanyan.im.enums.IMGroupType;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.mq.client.response.MqResponse;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.apiresp.RespPlaceLocation;
import com.quanyan.search.entity.request.ReqClubSearchInfo;
import com.quanyan.search.entity.response.ClubSearchResponse;
import com.quanyan.search.entity.response.SearchResponses;
import com.quanyan.search.service.impl.ClubSearchServiceImpl;
import com.quanyan.statium.api.resp.ResGameEvent;
import com.quanyan.statium.api.resp.ResPoints;
import com.quanyan.statium.service.StadiumOpenService;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import org.apache.commons.lang.time.StopWatch;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhuo.shi on 2016/5/30.
 */
@Service("clubService")
public class ClubServiceImpl  extends BaseServiceImpl implements ClubService{
    private static Logger logger = LoggerFactory.getLogger(ClubServiceImpl.class);
    private final String CREATE_CLUB = "CREATE_CLUB";
    private final String CLUB_PURPOSE = "CLUB_PURPOSE";
    private final String CLUB_INTRODUCE ="CLUB_INTRODUCE";

    @Autowired
    ThreadPoolTaskExecutor executor;

    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbClubMultimediaMapper clubMultimediaMapper;
    @Autowired
    private TbClubActivityMapper clubActivityMapper;
    @Autowired
    private TbClubAnnouncementMapper clubAnnouncementMapper;
    @Autowired
    private TbMedalMapper medalMapper;
    @Autowired
    private TbClubMedalRelationMapper clubMedalRelationMapper;
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Autowired
    private TbClubTypeMapper clubTypeMapper;
    @Autowired
    private TbClubSystemLogoMapper clubSystemLogoMapper;
    @Autowired
    private TbClubOnlineAccountMapper clubOnlineAccountMapper;
    @Autowired
    private TbClubOfflineAccountMapper clubOfflineAccountMapper;
    @Autowired
    private ClubOpenService clubOpenService;
    @Autowired
    private StadiumOpenService stadiumOpenService;
    @Autowired
    private PlaceClient<RespPlaceLocation> placeClient;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private ClubAccountExtendMapper clubAccountExtendMapper;
    @Autowired
    private TbClubPropertyMapper clubPropertyMapper;
    @Autowired
    private TbProvinceMapper provinceMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private CppService clubIMService;
    @Autowired
    @Qualifier("personCenterTaskClient")
    private QcMsgClient qcMsgClient;
    @Value("${quanyan_base_url}")
    private String quanyanBaseUrl;
    @Value("${club_share_url}")
    private String clubShareUrl;
    @Autowired
    private ClubXpLevelProducer clubXpLevelProducer;
    @Autowired
    private TbLevelMapper tbLevelMapper;
    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private TbActivityPosterMapper posterMapper;
//    @Autowired
//    private ClubActivityService clubActivityService;
    @Autowired
    private ActivitySupportService activitySupportService;
    @Autowired
    private ClubOpenExtendMapper clubOpenExtendMapper;
    @Autowired
    private ClubMedalService clubMedalService;

    private ClubSearchServiceImpl clubSearchService;
    @PostConstruct
    protected  void init(){
        clubSearchService = new ClubSearchServiceImpl(searchCloudUrl);
    }

    @Autowired
    private CppService cppService;

    @Autowired
    private TbClubOnlineMemberAccountMapper clubOnlineMemberAccountMapper;
    @Autowired
    private ClubIntegralService clubIntegralService;
    @Autowired
    private PullClubSupportService pullClubSupportService;

    /**
     * 创建俱乐部
     * @param club  创建俱乐部请求对象
     * @return      俱乐部基本信息对象
     */
    @Override
    @Transactional
    public RespClubBaseInfo saveClub(Integer uid, ReqClub club) {

        //如果这个城市已经存在了此俱乐部名称，城市等
        validateClubName(club);

        TbClub tbClub = new TbClub();
        tbClub.setUid(uid);
        tbClub.setLogoUrl(club.getLogoUrl());
        Integer clubTypeId = club.getClubType();
        if (clubTypeId != null) {
            TbClubTypeExample example = new TbClubTypeExample();
            example.createCriteria().andCategoryIdEqualTo(clubTypeId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            List<TbClubType> clubTypes = clubTypeMapper.selectByExample(example);
            if (clubTypes != null && clubTypes.size() > 0) {
                tbClub.setBgUrl(clubTypes.get(0).getBgUrl());
                tbClub.setClubType(clubTypeId);
            }
        }
        tbClub.setClubName(club.getClubName());
        tbClub.setSportName(club.getSportName());
        tbClub.setCityId(club.getCityId());
        tbClub.setDistrictId(club.getDistrictId());
        tbClub.setPurpose(club.getPurpose());
        tbClub.setIntroduce(club.getIntroduce());
        tbClub.setJoinType((byte)club.getJoinType());
        tbClub.setResidentPlaceId(club.getResidentPlaceId());
        tbClub.setPlaceBindId(club.getResidentPlaceId());
        tbClub.setResidentPlaceName(club.getResidentPlaceName());
        tbClub.setPlaceLat(club.getLat());      //场馆经纬度
        tbClub.setPlaceLng(club.getLng());
        tbClub.setOpenMembers(club.getOpenMembers());

        //对于足球俱乐部
        tbClub.setClubPropertyId(club.getClubPropertyId());
        tbClub.setClubPropertyChildId(club.getClubPropertyChildId());
        tbClub.setHomeTeamColor(club.getHomeTeamColor());
        tbClub.setGuestTeamColor(club.getGuestTeamColor());
        tbClub.setFoundDate(new Date());
        RespUserInfoBase userInfoBase = getUserInfoBase(tbClub.getUid());
        if (userInfoBase != null) {
            tbClub.setFounderNickname(userInfoBase.getNickName());
        }
        int ret = clubMapper.insertSelective(tbClub);
        if(ret != 1) {
            throw new BizException("创建俱乐部失败！");
        }

        //创建成功
        Integer clubId = tbClub.getId();

        //上传相册
        uploadMultiMedia(clubId, club.getMultiMediaList());

        //将管理员加入到俱乐部成员表，并设置角色为主席
        TbClubMember clubMember = new TbClubMember();
        clubMember.setClubId(clubId);
        clubMember.setUid(uid);
        clubMember.setIsTeamMember(Constants.NO);
        clubMember.setRoleCode(Constants.ClubRole.CLUB_ROLE_PRESIDENT);
        clubMember.setRoleName("主席");
        clubMember.setPriority(ClubMemberPriorityConstants.ROLE_CLUB_PRESIDENT_PRIORITY); //主席优先级
        clubMemberMapper.insertSelective(clubMember);
        clubMemberService.initClubMemberAccount(clubId, uid); //初始化账户
        //clubMemberService.insertClubMemberIndex(clubId, uid); //添加到搜索引擎

        //生成俱乐部线上账户
        TbClubOnlineAccount onlineAccount = new TbClubOnlineAccount();
        onlineAccount.setClubId(clubId);
        onlineAccount.setMoneyTotal(BigDecimal.ZERO);
        onlineAccount.setMoneyFreeze(BigDecimal.ZERO);
        onlineAccount.setMoneyUsable(BigDecimal.ZERO);
        onlineAccount.setIsDelete(Constants.IS_DELETE_FALSE);
        clubOnlineAccountMapper.insertSelective(onlineAccount);
        //生成俱乐部线下账户
        TbClubOfflineAccount offlineAccount = new TbClubOfflineAccount();
        offlineAccount.setClubId(clubId);
        offlineAccount.setMoneyTotal(BigDecimal.ZERO);
        offlineAccount.setIsDelete(Constants.IS_DELETE_FALSE);
        clubOfflineAccountMapper.insertSelective(offlineAccount);

        RespClubBaseInfo clubBaseInfo = convert2RespClubBaseInfo(uid, clubMapper.selectByPrimaryKey(clubId), false);
        //俱乐部分享链接地址
        StringBuilder sb = new StringBuilder();
        sb.append(clubShareUrl).append("?").append("clubId=").append(clubId);
        clubBaseInfo.setShareUrl(sb.toString());
        clubBaseInfo.setLat(club.getLat());
        clubBaseInfo.setLng(club.getLng());

        //添加俱乐部信息到solr cloud
        executor.submit(new ClubSolrIndexThread(clubBaseInfo, clubSearchService, false));
        //addClubInfo2SearchCloud(clubBaseInfo);

        //创建聊天室
        initClubIMGroup(tbClub);

        //推送个人中心任务消息
        pushUsercenterTaskMsg(clubId, uid);

        //初始化俱乐部勋章
        StopWatch sw = new StopWatch();
        sw.start();
        clubMedalService.initClubMedal(clubId,clubTypeId);

        //返回创建成功对象
        //初始化一条经验等级数据
        TbLevel tbLevel = new TbLevel();
        tbLevel.setType((byte)2);
        tbLevel.setNextLevelXp(0);
        tbLevel.setLevel(0);
        tbLevel.setXp(0);
        tbLevel.setCommonId(clubId);
        int n = tbLevelMapper.insertSelective(tbLevel);
        if (n>0) {
            /**************************通知mq，为该俱乐部添加经验***************************/
            RespClubXpLevelMsg respClubXpLevelMsg = getRespClubXpLevelMsg(clubId, tbClub.getUid());
            MqRequestMsg mqRequestMsg = getMqRequestMsg();

            if (StringUtil.isNotBlank(tbClub.getIntroduce())){
                respClubXpLevelMsg.setExpName(CLUB_INTRODUCE);
                mqRequestMsg.setBody(ObjectUtil.toByteArray(respClubXpLevelMsg));
                this.clubXpLevelProducer.syncSend(mqRequestMsg);
            }

            if (StringUtil.isNotBlank(tbClub.getPurpose())){
                respClubXpLevelMsg.setExpName(CLUB_PURPOSE);
                mqRequestMsg.setBody(ObjectUtil.toByteArray(respClubXpLevelMsg));
                this.clubXpLevelProducer.syncSend(mqRequestMsg);
            }
            /**************************通知mq，为该俱乐部添加经验***************************/
        }
        sw.stop();
        logger.warn("初始化个人中心任务clubId={},花费：{}", clubId, sw.getTime());
        //拉新用户
        if(isFirstClub(tbClub.getUid(), clubId)) {
            TbChannelUser tbChannelUser = pullClubSupportService.isPullUser(
                    tbClub.getUid(), null,
                    null, ClubConstants.PULL_STATUS_CLUB, null);
            if(null != tbChannelUser) {
                tbChannelUser.setClubId(clubId);
                pullClubSupportService.updatePullStatus(
                        tbChannelUser, ClubConstants.PULL_STATUS_CLUB);
            }
            logger.warn("不是拉新用户");
        }
        return clubBaseInfo;
    }

    public boolean isFirstClub(int uid, int clubId) {
        TbClubExample clubExample = new TbClubExample();
        clubExample.createCriteria().andUidEqualTo(uid);
        clubExample.setLimit(Limit.buildLimit(0,1));
        List<TbClub> clubs = clubMapper.selectByExample(clubExample);
        if(CollectionUtils.isEmpty(clubs)) {
            return false;
        }
        TbClub club = clubs.get(0);
        if(club.getId() == clubId) {
            logger.warn("uid:" + uid + "clubId:" + clubId + "是第一个俱乐部");
            return true;
        }
        return false;
    }

    private void validateClubName(ReqClub club){
//        Integer cityId = club.getCityId();
        String clubName = club.getClubName();
//        if (cityId == null){
//            throw new BizException("请确定俱乐部所在城市！");
//        }
        if (StringUtil.isBlankOrNull(clubName)){
            throw new BizException("俱乐部名称不能为空！");
        }
//        RespCity city = getCity(cityId);
//        String cityName = "";
//        if (city != null){
//            cityName = city.getName();
//        }
        TbClubExample example = new TbClubExample();
        example.createCriteria()
                .andClubNameEqualTo(clubName)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE); //名字全国唯一
        if (clubMapper.countByExample(example) > 0){
            throw new BizException("俱乐部名称已被使用，请重设！");
        }
    }

    @Autowired
    private TbIMExceptionLogMapper imExceptionLogMapper;
    /**
     * 初始化俱乐部聊天室
     */
    @Async
    private String initClubIMGroup(TbClub tbClub){
        StopWatch sw = new StopWatch();
        sw.start();
        ReqCreateIMGroup req = new ReqCreateIMGroup();
        req.setGroupname(tbClub.getClubName());
        req.setHead(tbClub.getLogoUrl());
        req.setGroupdescriptions(tbClub.getIntroduce());
        req.setIspublic(1);
        req.setOwner(tbClub.getUid());
        req.setType(IMGroupType.CLUB.getId());
        req.setCurrentUid(tbClub.getUid());
        req.setMaxusers(2000);      //群组成员最大数（包括群主）
        String groupid = clubIMService.createIMGroup(req);
        logger.info("创建俱乐部聊天室groupid=" + groupid);
        TbIMExceptionLog imExceptionLog = new TbIMExceptionLog();
        imExceptionLog.setUid(tbClub.getUid());
        imExceptionLog.setClubId(tbClub.getId());
        imExceptionLog.setClubName(tbClub.getClubName());
        imExceptionLog.setType(1); //创建俱乐部聊天组
        if (!StringUtil.isBlankOrNull(groupid)) {
            tbClub.setImGroupid(groupid);
            clubMapper.updateByPrimaryKeySelective(tbClub);
            //记录聊天室id创建成功
            imExceptionLog.setClubImGroupid(groupid);
            imExceptionLog.setState(1);
            imExceptionLogMapper.insertSelective(imExceptionLog);
        }else {
            //记录创建聊天室失败的俱乐部
            imExceptionLog.setState(0);
            imExceptionLogMapper.insertSelective(imExceptionLog);
        }
        sw.stop();
        logger.warn("创建俱乐clubId={}部聊天室，花费：{}", tbClub.getId(), sw.getTime());
        return groupid;
    }

    /**
     * 推送个人中心，新手任务通知
     * @param uid       俱乐部创建人id
     */
    @Async
    private void pushUsercenterTaskMsg(int clubId, int uid){
//        if (userTaskServiceFacade.isTaskComplete(uid, TaskEnum.TASK_ENUM__CREATE_CLUB.getId())){
//            return;
//        }
        StopWatch sw = new StopWatch();
        sw.start();

        UserTaskMsg userTaskMsg = new UserTaskMsg();
        userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__CREATE_CLUB.getId());
        userTaskMsg.setUid(uid);
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setTopic(Constants.MQ_TOPIC_TASK_TOPIC);
        mqRequestMsg.setTag(Constants.MQ_TOPIC_TASK_TAG);
        mqRequestMsg.setBody(ObjectUtil.toByteArray(userTaskMsg));
        qcMsgClient.asyncSend(mqRequestMsg);

        sw.stop();
        logger.warn("推送个人中心任务成功，clubId={}, 花费：{}", clubId, sw.getTime());
    }

    /**
     * 将俱乐部信息添加到搜索引擎索引，
     *      需要维护的索引字段：club_name, club_founder_nickname, club_integral, club_logo, club_level, club_star
     * @param clubBaseInfo      俱乐部信息
     */
//    @Async
//    private void addClubInfo2SearchCloud(RespClubBaseInfo clubBaseInfo){
//        logger.warn("-------------------000");
//        StopWatch sw = new StopWatch();
//        sw.start();
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        ClubIndexInfo indexInfo = new ClubIndexInfo();
//        indexInfo.setClub_id(String.valueOf(clubBaseInfo.getClubId()));
//        indexInfo.setClub_name(clubBaseInfo.getClubName());
//        RespCity city = clubBaseInfo.getCity();
//        if (city != null) {
//            indexInfo.setClub_city_id(city.getId());
//            indexInfo.setClub_city_name(city.getName());
//        }
//        RespDistrict district = clubBaseInfo.getDistrict();
//        if (district != null){
//            indexInfo.setClub_district_id(district.getId());
//            indexInfo.setClub_district_name(district.getName());
//        }
//        indexInfo.setClub_logo(clubBaseInfo.getClubLogo());
//        indexInfo.setClub_founder_nickname(clubBaseInfo.getUsername());
//        indexInfo.setClub_founder_uid(clubBaseInfo.getUid());
//        indexInfo.setClub_sport_name(clubBaseInfo.getSportName());
//        indexInfo.setClub_star(clubBaseInfo.getStar()==null?0d:clubBaseInfo.getStar());
//        indexInfo.setClub_integral(clubBaseInfo.getIntegral()==null?0:clubBaseInfo.getIntegral());
//        indexInfo.setClub_level(clubBaseInfo.getLevel()==null?0:clubBaseInfo.getLevel());
//        indexInfo.setClub_type_id(clubBaseInfo.getClubType());
//        indexInfo.setResident_place_id(clubBaseInfo.getResidentPlaceId());
//        logger.warn("-------------------0000");
//        logger.warn("searchCloudUrl="+searchCloudUrl);
//        APIResponse response = clubSearchService.insertDoc(indexInfo);
//        if (response == null || !response.isRet()){
//            logger.warn("添加俱乐部索引失败：{}", JSON.toJSON(response));
//            logger.warn("club index info:" + JSON.toJSONString(clubBaseInfo));
//        }else {
//            logger.debug("添加俱乐部clubId={}索引成功", clubBaseInfo.getClubId());
//        }
//        logger.warn("添加俱乐部clubId={}索引，花费：{}", clubBaseInfo.getClubId(), sw.getTime());
//    }

    //@Async
    //@Transactional
//    private void updateClubInfo2SearchCloud(Integer uid, TbClub tbClub){
//        logger.warn("-------------------0");
//        StopWatch sw = new StopWatch();
//        sw.start();
//        RespClubBaseInfo clubBaseInfo = convert2RespClubBaseInfo(uid, tbClub, false);
//        //先删除
//        APIResponse response = clubSearchService.deleteDocById(tbClub.getId());
//        if (!response.isRet()){
//            //throw new BizException("删除俱乐部"+tbClub.getId()+"索引失败，"+ response.getErrmsg());
//            logger.warn("删除俱乐部"+tbClub.getId()+"索引失败，"+ response.getErrmsg());
//        }
//        logger.warn("-------------------00");
//        //添加俱乐部信息到solr cloud
//        addClubInfo2SearchCloud(clubBaseInfo);
//        sw.stop();
//        logger.warn("更新俱乐部clubId={}索引，花费：{}",tbClub.getId(), sw.getTime());
//    }

    /**
     * 俱乐部详情
     * @param clubId    俱乐部ID
     * @return          俱乐部详细信息对象
     */
    @Override
    public RespClubDetail queryClubDetail(Integer uid, @NotNull Integer clubId) {
        RespClubDetail clubDetail = new RespClubDetail();
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        if(null == club) {
            return null;
        }
        clubDetail.setClubId(club.getId());
        //是否官方授权
        byte isAuthorize = club.getIsAuthorize();
        clubDetail.setAuthorize(isAuthorize==Constants.IS_YES);
        //类型、名称、logo
        clubDetail.setClubType(club.getClubType());
        clubDetail.setClubLogo(club.getLogoUrl());
        clubDetail.setClubName(club.getClubName());
        TbClubMultimediaExample multimediaExample = new TbClubMultimediaExample();
        multimediaExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        multimediaExample.setOrderByClause(" create_time desc");
        List<TbClubMultimedia> clubMultimediaList = clubMultimediaMapper.selectByExample(multimediaExample);
        clubDetail.setMultiMediaSize(clubMultimediaMapper.countByExample(multimediaExample));
        if (clubMultimediaList!= null && clubMultimediaList.size()>3){
            clubMultimediaList = clubMultimediaList.subList(0, 3); //三张照片
        }
        clubDetail.setMultiMediaList(clubMultimediaList);
        //当前查看详情的用户，是否已经加入此俱乐部
        boolean isJoin = false;
        if (uid != null && uid != 0){
            isJoin = clubMemberService.isClubMember(uid, clubId);
            clubDetail.setJoinAuditStatus(clubMemberService.getJoinClubStatus(clubId, uid));
            //是否有未读公告
            clubDetail.setAncetCanbeRead(clubOpenService.isHaveNotReadAnnouncement(clubId, uid));
            TbClubMemberExample example = new TbClubMemberExample();
            example.createCriteria().andUidEqualTo(uid)
                    .andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            List<TbClubMember> clubMembers = clubMemberMapper.selectByExample(example);
            if (clubMembers != null && clubMembers.size() >0 ){
                clubDetail.setRoleCode(clubMembers.get(0).getRoleCode());
            }
        }
        clubDetail.setJoin(isJoin);
        //我在此俱乐部中的会费
        if (isJoin){
            clubDetail.setClubMemberFund(this.getClubMemberFund(clubId, uid));
        }
        clubDetail.setJoinType((int)club.getJoinType());//加入是否需要验证
        //宗旨、介绍
        clubDetail.setPurpose(club.getPurpose());
        clubDetail.setIntroduce(club.getIntroduce());
        //常驻场馆
        clubDetail.setResidentPlaceId(club.getResidentPlaceId());
        clubDetail.setResidentPlaceName(club.getResidentPlaceName());
        //所在地
        clubDetail.setCity(getCity(club.getCityId()));
        clubDetail.setDistrict(getDistrict(club.getDistrictId()));
        //俱乐部背景图片
        clubDetail.setBgUrl(club.getBgUrl());
        //俱乐部属性
        TbClubProperty cp1 = getClubProperty(club.getClubPropertyId()); //一级属性
        TbClubProperty cp2 = getClubProperty(club.getClubPropertyChildId()); //二级属性
        if (cp1 != null) {
            clubDetail.setClubProperty(cp1.getPropertyName());
        }
        if (cp2 != null) {
            clubDetail.setClubChildProperty(cp2.getPropertyName());
        }
        //主客队队服颜色
        clubDetail.setHomeTeamColor(club.getHomeTeamColor());
        clubDetail.setGuestTeamColor(club.getGuestTeamColor());
        //运动类型名称
        clubDetail.setSportName(club.getSportName());
        //骑行总公里数
        clubDetail.setTotalKm(club.getTotalKm());
        //成立日期
        clubDetail.setFoundDate(club.getFoundDate().getTime());
        //积分、星级、等级
        clubDetail.setIntegral(club.getIntegral());
        clubDetail.setStar(club.getStar());
        clubDetail.setLevel(club.getLevel());
        //全国、地区排名
        clubDetail.setNationwideRanking(getClubRanking(clubId, null));
        clubDetail.setCityRanking(getClubRanking(clubId, club.getCityId()));
        //荣誉墙
        clubDetail.setMedalList(getClubMedals(clubId,club.getClubType()));
        //代表队成员, 获取第一页
        clubDetail.setClubTeam(clubMemberService.listClubTeamMembers(uid, clubId,
                Constants.DEFAULT_PAGE_INDEX, Constants.DEFAULT_PAGE_SIZE));
        //俱乐部成员
        clubDetail.setClubMember(clubMemberService.listClubMembers(uid, clubId, false, true,
                Constants.DEFAULT_PAGE_INDEX, Constants.DEFAULT_PAGE_SIZE));
        //审核状态
        RespUserInfoDetail userInfoBase = getUserDetailInfo(club.getUid());
        if (userInfoBase != null){
            //实名认证状态：0为未认证，1为认证中，2为认证通过，3为认证失败
            clubDetail.setIdentityStatus(userInfoBase.getNameVerifyStatusDe());
        }else {
            clubDetail.setIdentityStatus((byte)0);
        }
        //俱乐部最新活动
        clubDetail.setLatestActivity(this.getLatestClubActivity(clubId));
        try {
            //俱乐部最新赛事（rpc调用）
            ResGameEvent game = stadiumOpenService.getResGameEventByClubId(clubId);
            clubDetail.setLatestGame(game);
        }catch (Exception e){
            logger.error("调用 stadiumOpenService。getResGameEventByClubId()，异常：" + e.getMessage());
        }
        //最新一条公告
        clubDetail.setLatestAnnoucement(this.getLatestClubAnnouncement(clubId));
        //聊天室id
        clubDetail.setChatgroupid(club.getImGroupid());
        //俱乐部分享链接地址
        StringBuilder sb = new StringBuilder();
        sb.append(clubShareUrl).append("?").append("clubId=").append(clubId);
        clubDetail.setShareUrl(sb.toString());
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria()
                .andIsDeleteEqualTo(Constants.BYTE_ZERO).andClubIdEqualTo(clubId);
        int count = clubActivityMapper.countByExample(clubActivityExample);
        clubDetail.setHasActivity(count > 0 ? 1:0);
        return clubDetail;
    }

    /**
     * 计算俱乐部成员在俱乐部中资金
     * @param clubId        俱乐部
     * @param uid           俱乐部成员用户ID
     * @return
     */
    private BigDecimal getClubMemberFund(Integer clubId, Integer uid){
//        Map<String, Object> map = new HashMap<>();
//        map.put("clubId", clubId);
//        map.put("uid", uid);
//        RespClubMemberRemainder remainder = clubAccountExtendMapper.memberRemainder(map);
//        if (remainder == null) {
//            return BigDecimal.ZERO;
//        }
//        return remainder.getOfflineMoneyTotal().add(remainder.getOnlineMoneyTotal());

        TbClubOnlineMemberAccountExample example = new TbClubOnlineMemberAccountExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andUidEqualTo(uid)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOnlineMemberAccount> clubOnlineMemberAccounts = clubOnlineMemberAccountMapper.selectByExample(example);
        if (clubOnlineMemberAccounts != null && clubOnlineMemberAccounts.size() != 0) {
            return  clubOnlineMemberAccounts.get(0).getMoneyTotal();
        }

        return BigDecimal.ZERO;
    }

    /**
     * 设置俱乐部信息
     * @param reqClub       俱乐部更新请求类
     * @return     成功
     *              俱乐部不存在
     *              俱乐部名称不能被更改
     */
    @Override
    @Transactional
    public BaseEnum updateClub(Integer uid, ReqClub reqClub) {
        StopWatch sw1 = new StopWatch();
        sw1.start();
        TbClub tbClub = clubMapper.selectByPrimaryKey(reqClub.getClubId());
        if (tbClub == null){
           return ApiResponseEnum.RECORD_DO_NOT_EXISTS;
        }

        tbClub.setId(reqClub.getClubId());
        //logo
        tbClub.setLogoUrl(reqClub.getLogoUrl());
        //更新相册（添加相片）
        this.uploadMultiMedia(tbClub.getId(), reqClub.getMultiMediaList());
        //俱乐部名称只能更新一次
        String clubName = reqClub.getClubName();
        if (!StringUtil.isBlankOrNull(clubName) && !clubName.equals(tbClub.getClubName())) { // 如果传的俱乐部名称和原先一样，忽略
            validateClubName(reqClub);
            tbClub.setClubName(clubName);
            tbClub.setClubNameAlertCount(tbClub.getClubNameAlertCount() + 1);
        }
        if (reqClub.getOpenMembers() != null){
            tbClub.setOpenMembers(reqClub.getOpenMembers());
        }
        //对于足球俱乐部
        String hc = reqClub.getHomeTeamColor();
        if (hc != null) {
            tbClub.setHomeTeamColor(hc);
        }
        String gc = reqClub.getGuestTeamColor();
        if (gc != null) {
            tbClub.setGuestTeamColor(gc);
        }
        //宗旨、介绍、加入方式
        String purpose =  reqClub.getPurpose();
        if (purpose != null) {
            tbClub.setPurpose(purpose);
        }
        String introduce = reqClub.getIntroduce();
        if (introduce != null) {
            tbClub.setIntroduce(introduce);
        }
        byte jointype = (byte)reqClub.getJoinType();
        tbClub.setJoinType(jointype);

        //城市区域id, 社会属性，常驻场馆
        Integer cityId = reqClub.getCityId();
        if (cityId != null && cityId != 0) {
            tbClub.setCityId(cityId);
        }
        Integer districtId = reqClub.getDistrictId();
        if (districtId != null && districtId != 0) {
            tbClub.setDistrictId(reqClub.getDistrictId());
        }
        Integer p1Id = reqClub.getClubPropertyId();
        if (p1Id != null && p1Id != 0) {
            tbClub.setClubPropertyId(p1Id);
        }
        Integer p2Id = reqClub.getClubPropertyChildId();
        if (p2Id != null && p2Id != 0) {
            tbClub.setClubPropertyChildId(reqClub.getClubPropertyChildId());
        }
        Integer placeId = reqClub.getResidentPlaceId();
        if (placeId != null && placeId != 0){
            tbClub.setResidentPlaceId(placeId);
        }
        String placeName = reqClub.getResidentPlaceName();
        if (placeName != null) {
            tbClub.setResidentPlaceName(placeName);
        }
        Double lat = reqClub.getLat();
        if (lat != null && lat != 0) {
            tbClub.setPlaceLat(lat);
        }
        Double lng = reqClub.getLng();
        if (lng != null && lng != 0) {
            tbClub.setPlaceLng(lng);
        }
        int ret = clubMapper.updateByPrimaryKeySelective(tbClub);
        if (ret != 1) {
            throw new BizException("更新俱乐部失败！");
        }
        logger.warn("更新clubId={} 执行sql花费：{}", reqClub.getClubId(), sw1.getTime());
        logger.warn("-------------------1");
        //  更新索引
        RespClubBaseInfo clubBaseInfo = convert2RespClubBaseInfo(null, clubMapper.selectByPrimaryKey(reqClub.getClubId()), false);
        clubBaseInfo.setGoingActivityCount(activitySupportService.countActivityAfterWeek(tbClub.getId()));
        clubBaseInfo.setLat(tbClub.getPlaceLat());
        clubBaseInfo.setLng(tbClub.getPlaceLng());
        RespClubIntegralRank integralRank = clubIntegralService.getClubIntegralRankByClubId(tbClub.getId(), tbClub.getClubType());
        if (integralRank != null) {
            BigDecimal star = new BigDecimal(integralRank.getClubStar());
            star = star.setScale(1, BigDecimal.ROUND_HALF_UP);      //只保留一位小数，四舍五入
            clubBaseInfo.setStar(star.doubleValue());
        }
        executor.submit(new ClubSolrIndexThread(clubBaseInfo, clubSearchService, true));
        //updateClubInfo2SearchCloud(null, tbClub);

        logger.warn("-------------------2");
        StopWatch sw = new StopWatch();
        sw.start();
        //  更新聊天群组头像和logo
        ModifyIMGroup modifyIMGroup = new ModifyIMGroup();
        modifyIMGroup.setGroupid(tbClub.getImGroupid());
        modifyIMGroup.setGroupdescriptions(reqClub.getIntroduce());
        modifyIMGroup.setGroupname(reqClub.getClubName());
        modifyIMGroup.setHead(reqClub.getLogoUrl());
        modifyIMGroup.setExtid(tbClub.getId());
        modifyIMGroup.setType(2);  //俱乐部群
        modifyIMGroup.setMaxusers(5000);
        modifyIMGroup.setCurrentUid(uid);
        cppService.modifyGroup(modifyIMGroup);
        sw.split();
        logger.warn("更新俱乐部clubId={}的IM聊天组，花费：{}", tbClub.getId(), sw.getTime());

        //  俱乐部经验
        RespClubXpLevelMsg respClubXpLevelMsg = getRespClubXpLevelMsg(tbClub.getId(), tbClub.getUid());
        MqRequestMsg mqRequestMsg = getMqRequestMsg();
        if (StringUtil.isBlankOrNull(purpose) && StringUtil.isNotBlank(reqClub.getPurpose())){
            // 向 Mq发消息
            respClubXpLevelMsg.setExpName(CLUB_PURPOSE);
            mqRequestMsg.setBody(ObjectUtil.toByteArray(respClubXpLevelMsg));
            this.clubXpLevelProducer.syncSend(mqRequestMsg);
        }
        if (StringUtil.isBlankOrNull(introduce) && StringUtil.isNotBlank(reqClub.getIntroduce())){
            // 向 Mq发消息
            respClubXpLevelMsg.setExpName(CLUB_INTRODUCE);
            mqRequestMsg.setBody(ObjectUtil.toByteArray(respClubXpLevelMsg));
            this.clubXpLevelProducer.syncSend(mqRequestMsg);
        }
        sw.stop();
        logger.warn("更新俱乐部clubId={}经验，花费：{}", tbClub.getId(), sw.getTime());
        return ApiResponseEnum.SUCCESS;
    }

    private MqRequestMsg getMqRequestMsg() {
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setMsgId(UUID.randomUUID().toString());
        mqRequestMsg.setTopic(MqConstants.CLUB_XP_LEVEL_TOPIC_NAME);
        mqRequestMsg.setFlag(0);
        mqRequestMsg.setTag(MqConstants.CLUB_XP_LEVEL_TAGS_NAME);
        return mqRequestMsg;
    }

    private RespClubXpLevelMsg getRespClubXpLevelMsg(Integer id, Integer uid) {
        RespClubXpLevelMsg respClubXpLevelMsg = new RespClubXpLevelMsg();
        respClubXpLevelMsg.setClubId(id);
        respClubXpLevelMsg.setUid(uid);
        return respClubXpLevelMsg;
    }

    /**
     * 我创建的俱乐部列表（分页）
     * @param uid               用户ID
     * @param clubListPage      分页请求对象
     * @return
     */
    @Override
    public List<RespClubBaseInfo> listMyCreateClubs(@NotNull Integer uid, ReqClubPage clubListPage) {
        Map<String, Object> params = clubListPage.getParamMap();
        TbClubExample tbClubExample = new TbClubExample();
        TbClubExample.Criteria criteria = tbClubExample.createCriteria();
        criteria.andUidEqualTo(uid)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);  //我创建的
        if (params.containsKey("cityId")){
            criteria.andCityIdEqualTo(Integer.valueOf(params.get("cityId").toString()));
        }
        if (params.containsKey("clubTypeId")){
            criteria.andClubTypeEqualTo(Integer.valueOf(params.get("clubTypeId").toString()));
        }
        tbClubExample.setOrderByClause(" create_time desc");
        if (clubListPage.getPageNum() != null && clubListPage.getPageSize() != null){
            tbClubExample.setLimit(Limit.buildLimit(clubListPage.getPageNum() + 1, clubListPage.getPageSize()));     //分页对象
        }
        List<TbClub> clubList = clubMapper.selectByExample(tbClubExample);
        List<RespClubBaseInfo> respClubBaseInfos = new ArrayList<>();
        if (clubList != null) {
            logger.warn("listMyCreateClubs clubList size=" + clubList.size());
            for (TbClub tbClub : clubList){
                respClubBaseInfos.add(this.convert2RespClubBaseInfo(uid, tbClub, false)); //uid传null,我创建的不需要看审核状态
            }
        }
        return respClubBaseInfos;
    }

    /**
     * 我创建的俱乐部总个数
     * @param uid       用户id
     * @return
     */
    @Override
    public Integer countMyCreateClubs(@NotNull Integer uid) {
        TbClubExample tbClubExample = new TbClubExample();
        tbClubExample.createCriteria().andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        return clubMapper.countByExample(tbClubExample);
    }

    /**
     * 我加入的俱乐部列表(包含了审核中、通过的、拒绝的)
     * @param uid               用户id
     * @param clubListPage      请求分页对象
     * @return
     */
    @Override
    public List<RespClubBaseInfo> listMyJoinedClubs(Integer uid, ReqClubPage clubListPage) {
//        TbClubMemberApplyExample tbClubMemberApplyExample = new TbClubMemberApplyExample();
//        tbClubMemberApplyExample.createCriteria()
//                .andUidEqualTo(uid)
//
//                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
//        tbClubMemberApplyExample.setLimit(Limit.buildLimit(clubListPage.getPageNum(), clubListPage.getPageSize()));     //分页对象
//        List<TbClubMemberApply> tbClubMemberApplies = clubMemberApplyMapper.selectByExample(tbClubMemberApplyExample);

        Map<String, Object> map = clubListPage.getParamMap();
        map.put("uid", uid);
        if (clubListPage.getPageNum() != null && clubListPage.getPageSize() != null){
            Limit limit = Limit.buildLimit(clubListPage.getPageNum() + 1, clubListPage.getPageSize());
            map.put("start", limit.getStart());
            map.put("pageSize", limit.getSize());
        }
        List<Integer> clubIds = sqlSessionTemplate.selectList("selectMyJoinedClubs", map);

        List<RespClubBaseInfo> respClubBaseInfos = new ArrayList<>();
        for (int clubId : clubIds){
            TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
            respClubBaseInfos.add(this.convert2RespClubBaseInfo(uid, tbClub, true));
        }
        return respClubBaseInfos;
    }

    /**
     * 我加入的俱乐部总个数
     * @param uid        用户id
     * @return
     */
    @Override
    public Integer countMyJoinedClubs(Integer uid, ReqClubPage clubListPage) {
//        TbClubMemberApplyExample tbClubMemberApplyExample = new TbClubMemberApplyExample();
//        tbClubMemberApplyExample.createCriteria().andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
//        return clubMemberApplyMapper.countByExample(tbClubMemberApplyExample);
        Map<String, Object> map = clubListPage.getParamMap();
        map.put("uid", uid);
        return sqlSessionTemplate.selectOne("countMyJoinedClubs", map);
    }

    /**
     * 搜索俱乐部
     * @param  uid              当前搜索的用户id
     * @param reqClubSearch     请求搜索对象
     * @return
     */
    @Override
    public PageObj<List<RespClubBaseInfo>> searchClubs(Integer uid, ReqClubSearch reqClubSearch) {

        List<RespClubBaseInfo> list = new ArrayList<>();
        int total = 0;
        ReqClubSearchInfo searchInfo = new ReqClubSearchInfo();
        String keyword = reqClubSearch.getKeyword();
        if (!StringUtil.isBlankOrNull(keyword)){
            searchInfo.setClub_name(keyword);
            searchInfo.setClub_founder_nickname(keyword);
        }else {
            //如果是填入了搜索词，不进行排序
            Map<String, String> sortMap = new HashMap<>();
            Integer sortBy = reqClubSearch.getSortBy();
            if (sortBy == null || sortBy == 1){
                sortMap.put("club_integral", "desc"); // 按积分排序
            }else if (sortBy == 2){
                sortMap.put("club_star", "desc");     // 按评价排序
            }else if (sortBy == 3){
                sortMap.put("club_level", "desc");    // 按等级排序
            }
            searchInfo.setSortMap(sortMap);
        }
        if (reqClubSearch.getCityId() != null && reqClubSearch.getCityId() != -1) {
            searchInfo.setCity_id(reqClubSearch.getCityId());
        }
        if (reqClubSearch.getDistrictId() != null && reqClubSearch.getDistrictId() != -1){
            searchInfo.setDistrict_id(reqClubSearch.getDistrictId());
        }
        if (reqClubSearch.getClubTypeId() != null && !reqClubSearch.getClubTypeId().equals(-1)){
            searchInfo.setClub_type_id(reqClubSearch.getClubTypeId());
        }
        if (reqClubSearch.getResidentPlaceId() != null && reqClubSearch.getResidentPlaceId() != -1){
            searchInfo.setResident_place_id(reqClubSearch.getResidentPlaceId());
        }
        searchInfo.setPageNo(reqClubSearch.getPageNo());
        searchInfo.setPageSize(reqClubSearch.getPageSize());

        APIResponse<SearchResponses<List<ClubSearchResponse>>> response = clubSearchService.searchClubInfoList(searchInfo);
        if (null != response && response.isRet()){
            SearchResponses<List<ClubSearchResponse>> searchResponse = response.getData();
            if (searchResponse != null) {
                List<ClubSearchResponse> searchResult = searchResponse.getData();
                for (ClubSearchResponse clubSearchResponse : searchResult){
                    RespClubBaseInfo baseInfo = new RespClubBaseInfo();
                    int clubId = clubSearchResponse.getClub_id();
                    baseInfo.setClubId(clubId);
                    baseInfo.setClubLogo(clubSearchResponse.getClub_logo());
                    baseInfo.setClubName(clubSearchResponse.getClub_name());
                    baseInfo.setLevel(clubSearchResponse.getClub_level());
                    baseInfo.setIntegral(clubSearchResponse.getClub_integral());
                    baseInfo.setStar(clubSearchResponse.getClub_star());
                    baseInfo.setClubType(clubSearchResponse.getClub_type_id());
                    baseInfo.setUsername(clubSearchResponse.getClub_founder_nickname());
                    baseInfo.setSportName(clubSearchResponse.getClub_sport_name());
                    RespCity city = new RespCity();
                    city.setName(clubSearchResponse.getCity_name());
                    baseInfo.setCity(city);
                    RespDistrict district = new RespDistrict();
                    district.setName(clubSearchResponse.getDistrict());
                    baseInfo.setDistrict(district);
                    TbClub tbClub = clubMapper.selectByPrimaryKey(clubSearchResponse.getClub_id());
                    if (tbClub != null) {
                        baseInfo.setJoinType((int)tbClub.getJoinType());
                        if (uid != null) {
                            baseInfo.setStatus(clubMemberService.getJoinClubStatus(clubId, uid));
                            baseInfo.setJoin(clubMemberService.isClubMember(uid, clubSearchResponse.getClub_id()));
                        }
                    }
                    //正在报名中的赛事场次
                    int goingGameCount = stadiumOpenService.countGameEventSigningByClubId(clubSearchResponse.getClub_id());
                    baseInfo.setGoingGamesCount(goingGameCount);
                    baseInfo.setGoingActivityCount(activitySupportService.countActivityAfterWeek(clubId)); //正在报名中的活动场次
                    baseInfo.setMemberCount(clubMemberService.countClubMembers(clubSearchResponse.getClub_id(),true));
                    list.add(baseInfo);
                }
                total = searchResponse.getTotal();
            }
        }
        return PageObj.create(total, reqClubSearch.getPageNo(), reqClubSearch.getPageSize(), list);
    }

    /**
     * 获取推荐的俱乐部列表
     * 推荐规则：按用户所在城市推荐
     * @return
     */
    @Override
    public List<RespClubBaseInfo> getRecommendClubs(Integer uid, ReqClubRecommend reqClubRecommend) {

        Double lat = reqClubRecommend.getLat();
        Double lng = reqClubRecommend.getLng();

        TbClubExample example = new TbClubExample();
        TbClubExample.Criteria criteria = example.createCriteria();

        Integer residentPlaceId = reqClubRecommend.getResidentPlaceId();
        if (residentPlaceId != null && residentPlaceId != 0){
            criteria.andResidentPlaceIdEqualTo(residentPlaceId);
        }
        Integer sportTypeId = reqClubRecommend.getSportTypeId();
        if (sportTypeId != null && sportTypeId != 0){
            criteria.andClubTypeEqualTo(sportTypeId);
        }
        Integer cityId = reqClubRecommend.getCityId();
        if (cityId != null && cityId != 0){         //优先使用传过来的cityId
            criteria.andCityIdEqualTo(cityId);
        }else {                                     //如果没有cityId，从经纬度和用户个人信息中取cityId
            if (uid != null) {
                RespUserInfoBase userInfo = getUserInfoBase(uid);
                if (userInfo != null) {
                    cityId = userInfo.getAreaId();
                }
            }

            if (lat != null && lng != null) {
                BaiduLBS baiduLBS = new BaiduLBS();
                AddressComponent address = baiduLBS.getAddressComponentByLatAndLng(lat, lng);       //根据经纬度获取用户所在城市名
                String cityName = address.getCity();
                if(StringUtil.isBlankOrNull(cityName)){
                    cityId = getCityIdByName(cityName);
                }
            }
            if (cityId != null  && cityId != 0){
                criteria.andCityIdEqualTo(cityId);
            }
        }
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);

        example.setLimit(Limit.buildLimit(1, 50));
        example.setOrderByClause(" star DESC, id ASC"); //评分倒序，id正序
        List<TbClub> clubs = clubMapper.selectByExample(example);

        List<RespClubBaseInfo> clubBaseInfos = new ArrayList<>();
        for (TbClub tbClub : clubs){

            RespClubBaseInfo clubBaseInfo = this.convert2RespClubBaseInfo(uid, tbClub, false);
            double dist = 0;
            try {
                dist = DistanceUtil.getDistanceRice(tbClub.getPlaceLng(), tbClub.getPlaceLat(), lng, lat);
            }catch (Exception e) {
                dist = 10000;
            }
            clubBaseInfo.setDist(dist);
//            if (dist/1000 > 30){        //30公里以外的排除
//                continue;
//            }
            clubBaseInfo.setGoingActivityCount(activitySupportService.countActivityAfterWeek(tbClub.getId()));
            clubBaseInfo.setStar(clubIntegralService.updateSearchClubStar(tbClub.getId()));
            clubBaseInfos.add(clubBaseInfo);
        }
        Collections.sort(clubBaseInfos, new Comparator<RespClubBaseInfo>() {
            @Override
            public int compare(RespClubBaseInfo o1, RespClubBaseInfo o2) {
                if (o2.getStar() > o1.getStar()){
                    return 1;
                }else if (o2.getStar() < o1.getStar()){
                    return  -1;
                }else {
                    if (o1.getDist() > o2.getDist()) {
                        return 1;
                    } else if (o1.getDist() < o2.getDist()) {
                        return -1;
                    } else {      //距离相等，比较活动数
                        return (o2.getGoingActivityCount() - o1.getGoingActivityCount());
                    }
                }
            }
        });
        Integer size = reqClubRecommend.getSize();
        if (clubBaseInfos.size() > size){
            clubBaseInfos = clubBaseInfos.subList(0, size);
        }
        logger.warn("推荐的俱乐部：" + JSON.toJSONString(clubBaseInfos));
        return clubBaseInfos;
    }

    @Autowired
    private TbCityMapper cityMapper;
    @Autowired
    private TbDistrictMapper districtMapper;

    @Override
    public RespCityPage listCity(Double lat, Double lng){

        RespCityPage page = new RespCityPage();
        if (lat != null && lng != null) {
            BaiduLBS baiduLBS = new BaiduLBS();
            AddressComponent address = baiduLBS.getAddressComponentByLatAndLng(lat, lng);       //根据经纬度获取用户所在城市名
            if (address != null) {
                page.setLocateCityName(address.getCity());
                Integer cityId = getCityIdByName(address.getCity());
                if (cityId != null) {
                    page.setLocateCityId(cityId);
                    page.setLocateDistrictName(address.getDistrict());
                    List<TbDistrict> districts = getDistrictList(cityId);
                    for (TbDistrict district : districts) {
                        if (district.getName().equals(address.getDistrict())) {
                            page.setLocateDistrictId(district.getId());
                        }
                    }
                }
            }
        }
        TbCityExample cityExample = new TbCityExample();
        TbCityExample.Criteria criteria = cityExample.createCriteria();
                criteria.andIsEnableEqualTo(1);

        page.setCityList(getCities(cityExample));

        criteria.andIsRecommendEqualTo((byte)1);
        page.setHotCityList(getCities(cityExample));

        return page;
    }

    private List<RespCity> getCities(TbCityExample cityExample){

        List<TbCity> cityList = cityMapper.selectByExample(cityExample);
        List<RespCity> respCities = new ArrayList<>();
        if (cityList != null && cityList.size() != 0){
            for (TbCity tbCity : cityList) {
                RespCity respCity = new RespCity();
                respCity.setId(tbCity.getId());
                respCity.setName(tbCity.getName());
                String pinyin = PinYinUtils.hanyuToPinyin(tbCity.getName());
                if(!StringUtil.isBlankOrNull(pinyin)) {
                    respCity.setInitial(pinyin.substring(0,1));
                }
                TbDistrictExample districtExample = new TbDistrictExample();
                districtExample.createCriteria()
                        .andCityIdEqualTo(tbCity.getId());
                List<TbDistrict> districts = districtMapper.selectByExample(districtExample);
                List<RespDistrict> respDistricts = new ArrayList<>();
                for (TbDistrict district : districts){
                    RespDistrict respDistrict = new RespDistrict();
                    respDistrict.setId(district.getId());
                    respDistrict.setName(district.getName());
                    respDistricts.add(respDistrict);
                }
                respCity.setDistrictList(respDistricts);
                respCities.add(respCity);
            }
        }
        return respCities;
    }

    /**
     * 获取俱乐部类型列表
     * @return
     */
    @Override
    public List<RespClubType> listClubType(String ver) {
        List<RespClubType> list = new ArrayList<>();
        List<TbClubType> clubTypeList = this.getClubTypeList();
        if (clubTypeList.isEmpty()) {
            return list;
        } else {
            RespClubType respClubType;
            for (TbClubType tbClubType : clubTypeList) {
                int catetoryId = tbClubType.getCategoryId();
                if (!StringUtil.isBlankOrNull(ver)) {
                    try {
                        double version = Double.valueOf(ver.substring(0, 3));
                        if (version < 2.6  && (catetoryId == 10 | catetoryId == 5 || catetoryId == 24 || catetoryId == 9 || catetoryId == 6)){
                            continue;
                        }
                    }catch (Exception e){

                    }
                }else {
                    if ((catetoryId == 10 | catetoryId == 5 || catetoryId == 24 || catetoryId == 9 || catetoryId == 6)){
                        continue;
                    }
                }
                respClubType = new RespClubType();
                respClubType.setClubTypeName(tbClubType.getClubTypeName());
                respClubType.setIconUrl(tbClubType.getIconUrl());
                respClubType.setTypeId(tbClubType.getCategoryId());
                respClubType.setPriority(tbClubType.getPriority());
                list.add(respClubType);
            }
        }
        return list;
    }
    /**
     * 获取俱乐部系统LOGO列表
     * @return
     */
    @Override
    public List<RespClubSystemLogo> listClubSystemLogo() {
        List<RespClubSystemLogo> list = new ArrayList<>();
        List<TbClubSystemLogo> clubSystemLogoList = this.getClubSystemLogoList();
        if (clubSystemLogoList.isEmpty()) {
            return list;
        } else {
            RespClubSystemLogo clubSystemLogo;
            for (TbClubSystemLogo tbClubSystemLogo : clubSystemLogoList) {
                clubSystemLogo = new RespClubSystemLogo();
                clubSystemLogo.setClubLogoId(tbClubSystemLogo.getId());
                clubSystemLogo.setClubTypeId(tbClubSystemLogo.getClubTypeId());
                clubSystemLogo.setLogoName(tbClubSystemLogo.getLogoName());
                clubSystemLogo.setLogoUrl(tbClubSystemLogo.getLogoUrl());
                list.add(clubSystemLogo);
            }
        }
        return list;
    }

    /**
     * 获取俱乐部属性列表
     * @return
     */
    @Override
    public List<RespClubProperty> listClubProperty() {
        List<RespClubProperty> respClubPropertyList = new ArrayList<>();
        List<TbClubProperty> clubPropertyList = this.getClubPropertyList(0,1);
        if (clubPropertyList.isEmpty()) {
            return new ArrayList<>();
        } else {
            RespClubProperty respClubProperty;
            for (TbClubProperty tbClubProperty : clubPropertyList) {
                int parentId = tbClubProperty.getId();
                respClubProperty = new RespClubProperty();
                respClubProperty.setClubPropertyId(parentId);
                respClubProperty.setClubPropertyName(tbClubProperty.getPropertyName());
                List<TbClubProperty> list = this.getClubPropertyList(parentId,2);
                List<ClubPropertyChildren> clubPropertyChildrenList = new ArrayList<>();
                if (list.isEmpty()) {

                }else{
                    ClubPropertyChildren clubPropertyChildren;
                    for (TbClubProperty clubProperty : list) {
                        clubPropertyChildren = new ClubPropertyChildren();
                        clubPropertyChildren.setClubPropertyChildrenId(clubProperty.getId());
                        clubPropertyChildren.setClubPropertyChildrenName(clubProperty.getPropertyName());
                        clubPropertyChildrenList.add(clubPropertyChildren);
                    }
                    respClubProperty.setList(clubPropertyChildrenList);
                }
                respClubPropertyList.add(respClubProperty);
            }
        }
        return respClubPropertyList;
    }

    /**
     * 获取省市区列表
     * @return
     */
    @Override
    public RespSituation getSituationList(long lastUpdateTime) {
        RespSituation respSituation = new RespSituation();

        //判断数据是否过期:数据库中最后一条已开通城市记录
        List<TbCity> cityLastList = super.getCityList(0,0);
        if(!cityLastList.isEmpty()){
            long newLastUpdateTime = cityLastList.get(0).getUpdateTime().getTime();
            respSituation.setLastUpdatTime(newLastUpdateTime);
            if(newLastUpdateTime == lastUpdateTime){
                respSituation.setIsUpdate(false);
                return respSituation;
            }else{
                respSituation.setIsUpdate(true);
                //数据库中所有已开通城市记录
                List<TbProvince> provinceList = this.getEnableProvince(1);
                if (!provinceList.isEmpty()) {
                    List<RespClubProvince> respProvinceList = new ArrayList<>();
                    RespClubProvince prov;
                    for (TbProvince province : provinceList) {
                        prov = new RespClubProvince();
                        prov.setProvinceId(province.getId());
                        prov.setProvinceName(province.getName());
                        prov.setPriority(province.getPriority());
                        List<TbCity> cityList = super.getCityList(1,province.getId());
                        List<RespClubCity> respCityList = new ArrayList<>();
                        if (!cityList.isEmpty()) {
                            RespClubCity respCity;
                            for (TbCity tbCity : cityList) {
                                respCity = new RespClubCity();
                                int cityId = tbCity.getId();
                                respCity.setCityId(cityId);
                                respCity.setCityName(tbCity.getName());
                                List<TbDistrict> districtList = super.getDistrictList(cityId);
                                if (!districtList.isEmpty()) {
                                    List<RespClubDistrict> respDistrictList = new ArrayList<>();
                                    RespClubDistrict respDistrict;
                                    for (TbDistrict tbDistrict : districtList) {
                                        respDistrict = new RespClubDistrict();
                                        respDistrict.setDistrictId(tbDistrict.getId());
                                        respDistrict.setDistrictName(tbDistrict.getName());
                                        respDistrictList.add(respDistrict);
                                    }
                                    respCity.setRespDistrictList(respDistrictList);
                                }
                                respCityList.add(respCity);
                            }
                            prov.setRespCityList(respCityList);
                            respProvinceList.add(prov);
                        }
                    }
                    respSituation.setProvinceList(respProvinceList);
                }
            }
        }

        return respSituation;
    }


    /**
     * 上传俱乐部的多媒体文件
     * @param clubId        俱乐部ID
     * @param mediaList     多媒体列表
     */
    private void uploadMultiMedia(int clubId, List<TbClubMultimedia> mediaList){
        if (mediaList == null || mediaList.size() == 0){
            return;
        }
        for (int i = 0; i < mediaList.size(); i++){
            TbClubMultimedia multimedia = mediaList.get(i);
            multimedia.setClubId(clubId);
            clubMultimediaMapper.insertSelective(multimedia);
        }
    }

    /**
     * 获取某个俱乐部的勋章列表
     * @param clubId    俱乐部ID
     * @return
     */
    private List<TbMedal> getClubMedals(Integer clubId,Integer clubType){
        List<TbMedal> medals = new ArrayList<>();
        List<TbClubMedalRelation> clubMedalRelationList = clubMedalService.getClubMedalRelationList(clubId);
        if (clubMedalRelationList.isEmpty()) {
            clubMedalService.initClubMedal(clubId,clubType);
        } else {
            List<RespClubMedal> respClubMedalList = clubMedalService.listClubMedal(clubId,1);
            if (!respClubMedalList.isEmpty()) {
                TbMedal medal;
                for (RespClubMedal respClubMedal : respClubMedalList) {
                    medal = new TbMedal();
                    medal.setEmptyIcon(respClubMedal.getEmptyIcon());
                    medal.setIcon(respClubMedal.getIcon());
                    medal.setId(respClubMedal.getMedalId());
                    medal.setName(respClubMedal.getName());
                    medals.add(medal);
                }
            }

        }
        return medals;
    }

    /**
     *  获取最新一条俱乐部活动
     * @param clubId    俱乐部ID
     * @return
     */
    private RespClubActivityPlain getLatestClubActivity(Integer clubId){
        TbClubActivityExample activityExample = new TbClubActivityExample();
        activityExample.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO)
                .andActivityStatusIn(Arrays.asList(0f, 1f)); //未取消，未结束的活动
        activityExample.setOrderByClause(" create_time desc");
        List<TbClubActivity> clubActivityList = clubActivityMapper.selectByExample(activityExample);
        if(clubActivityList != null && clubActivityList.size() > 0){
            TbClubActivity tbActivity = clubActivityList.get(0);
            RespClubActivityPlain latestActivity = new RespClubActivityPlain();
            Integer activityId = tbActivity.getActivityId();
            ActivityInfo activityInfo = activityOpenService.queryOneActivityById(activityId);
            if (activityInfo != null){
                latestActivity.setActivityId(activityId);
                latestActivity.setName(activityInfo.getName());
                TbActivityPoster poster = posterMapper.selectByPrimaryKey(activityInfo.getPosterPicId());
                if (poster != null) {
                    latestActivity.setPosterUrl(poster.getUrl());
                }
                latestActivity.setStartTime(activityInfo.getStartTime());
                latestActivity.setEndTime(activityInfo.getEndTime());
                BigDecimal minPrice = BigDecimal.ZERO;
                int feeType = tbActivity.getFeeType();
                if (feeType == 0){      //AA
                    minPrice = tbActivity.getAaFee();
                }
                if (feeType == 1){      //固定费用
                    List<BigDecimal> feeList = new ArrayList<>();
                    feeList.add(tbActivity.getFemaleMemberFee());
                    feeList.add(tbActivity.getMaleMemberFee());
                    if(tbActivity.getSignUpType().equals(Constants.BYTE_ZERO))
                    {
                        feeList.add(tbActivity.getFemaleFee());
                        feeList.add(tbActivity.getMaleFee());
                    }
                    minPrice = Collections.min(feeList);
                }
                latestActivity.setPrice(minPrice);
                RespCity city = getCity(tbActivity.getCityId());
                if (city != null) {
                    latestActivity.setCityName(city.getName());
                }
                RespDistrict district = getDistrict(tbActivity.getDistrictId());
                if (district != null) {
                    latestActivity.setDistrictName(district.getName());
                }
                latestActivity.setActivityType(tbActivity.getActivityType());
                if (city == null || district == null){
                   latestActivity.setPlaceAddress(activityInfo.getPlaceAddress());
                }
                //活动状态
                int status = activityInfo.getStatus();
                long currentTime = System.currentTimeMillis();
                if (status == 2){
                    latestActivity.setStatus(1);        //已取消
                }else {
                    if (currentTime < activityInfo.getSignEndTime().getTime()){
                        if (activityInfo.getLimitNum().intValue() == activityInfo.getAlreadySignTotalNum().intValue() && activityInfo.getLimitNum() != 0) {
                            latestActivity.setStatus(2);  //已报满
                        } else {
                            latestActivity.setStatus(3);  //报名中
                        }
                    } else if (currentTime > activityInfo.getSignEndTime().getTime() && currentTime < activityInfo.getStartTime().getTime()) {
                        latestActivity.setStatus(4);        //报名截止
                    } else if (currentTime > activityInfo.getStartTime().getTime() && currentTime < activityInfo.getEndTime().getTime()) {
                        latestActivity.setStatus(5);        //活动进行中
                    } else if (currentTime > activityInfo.getEndTime().getTime()) {
                        latestActivity.setStatus(6);        //活动已经结束
                    }
                }

                return latestActivity;
            }
        }
        return null;
    }

    /**
     * 获取俱乐部最新一条公告
     * @param clubId        俱乐部ID
     * @return
     */
    private RespClubAnnouncement getLatestClubAnnouncement(Integer clubId){
        TbClubAnnouncementExample clubAnnouncementExample = new TbClubAnnouncementExample();
        clubAnnouncementExample.createCriteria().andClubIdEqualTo(clubId).andIsDeleteEqualTo((int)Constants.IS_DELETE_FALSE);
        clubAnnouncementExample.setOrderByClause(" create_time desc");
        List<TbClubAnnouncement> clubAnnouncements = clubAnnouncementMapper.selectByExample(clubAnnouncementExample);
        if (clubAnnouncements != null && clubAnnouncements.size() > 0){
            TbClubAnnouncement tbClubAnnouncement = clubAnnouncements.get(0);
            RespClubAnnouncement announcement = new RespClubAnnouncement();
            announcement.setClubId(clubId);
            announcement.setId(tbClubAnnouncement.getId());
            announcement.setContent(tbClubAnnouncement.getContent());
            announcement.setTitle(tbClubAnnouncement.getTitle());
            return announcement;
        }
        return  null;
    }

    /**
     * 获取俱乐部在全国的排名, 或地区（市级）的排名
     * @param clubId    俱乐部ID
     * @param cityId    城市ID
     * @return
     */
    @Override
    public int getClubRanking(Integer clubId, Integer cityId){
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        if(null == club){
            return 0;
        }
        //获取比当前俱乐部积分大的俱乐部个数
//        TbClubExample clubExample = new TbClubExample();
//        clubExample.createCriteria().andIntegralGreaterThanOrEqualTo(club.getIntegral());
//        if (cityId != null){
//            clubExample.createCriteria().andCityIdEqualTo(cityId); //地区排名筛选
//        }
//        List<TbClub> clubs = clubMapper.selectByExample(clubExample);
//        List<Double> integrals = new ArrayList<>();
//        for (TbClub club1 : clubs){
//            integrals.add(club1.getIntegral());
//        }
//        //如果积分相同，去重
//        List<Double> listWithoutDup = new ArrayList<>(new HashSet<>(integrals));
//        return listWithoutDup.size()+1;
        Map<String, Object> paramMap = new HashMap<>();
        if (cityId != null && cityId != 0){
            paramMap.put("cityId", cityId);
        }
        Integer sportTypeId = club.getClubType();
        if (sportTypeId != null){
            paramMap.put("sportTypeId", sportTypeId);
        }
        List<RespClubBaseInfo> list = sqlSessionTemplate.selectList("selectClubRankingList", paramMap);
        if (list != null && list.size() > 0){
            for (RespClubBaseInfo clubBaseInfo : list){
                if (clubBaseInfo.getClubId().intValue() == clubId){
                    return clubBaseInfo.getRanking();
                }
            }
        }
        return 0;
    }

    /**
     * 转化RespClubBaseInfo
     * @param uid           用户id
     * @param tbClub        俱乐部对象
     * @return
     */
    @Override
    public RespClubBaseInfo convert2RespClubBaseInfo(Integer uid, TbClub tbClub, boolean showAudit){
        if (tbClub == null){
            return null;
        }
        RespClubBaseInfo clubBaseInfo = new RespClubBaseInfo();
        clubBaseInfo.setClubId(tbClub.getId());
        clubBaseInfo.setSportName(tbClub.getSportName());
        clubBaseInfo.setClubName(tbClub.getClubName());
        clubBaseInfo.setClubLogo(tbClub.getLogoUrl());
        clubBaseInfo.setCityId(tbClub.getCityId());
        clubBaseInfo.setCity(getCity(tbClub.getCityId()));
        clubBaseInfo.setDistrict(getDistrict(tbClub.getDistrictId()));
        clubBaseInfo.setClubType(tbClub.getClubType());
        Integer placeId = tbClub.getResidentPlaceId();
        if (placeId != null && placeId != 0) {
            clubBaseInfo.setResidentPlaceId(placeId);
            List<RespPlaceLocation> latlng = placeClient.getPlaceLocation(Arrays.asList(placeId));
            if (latlng != null && latlng.size() > 0){
                clubBaseInfo.setLat(latlng.get(0).getLat());
                clubBaseInfo.setLng(latlng.get(0).getLng());
            }
        }else {
            clubBaseInfo.setLat(tbClub.getPlaceLat());
            clubBaseInfo.setLng(tbClub.getPlaceLng());
        }
        clubBaseInfo.setResidentPlaceName(tbClub.getResidentPlaceName());
        clubBaseInfo.setUid(tbClub.getUid());
        clubBaseInfo.setUsername(tbClub.getFounderNickname());
        clubBaseInfo.setIntegral(tbClub.getIntegral());
        clubBaseInfo.setJoinType((int)tbClub.getJoinType());
        clubBaseInfo.setLevel(tbClub.getLevel());
        clubBaseInfo.setStar(null);
        clubBaseInfo.setRanking(this.getClubRanking(tbClub.getId(), tbClub.getCityId()));
        if (showAudit) { //如果是我加入的，需要看审核状态
            clubBaseInfo.setStatus(clubMemberService.getJoinClubStatus(tbClub.getId(), uid));
        }
        clubBaseInfo.setMemberCount(clubMemberService.countClubMembers(tbClub.getId(), true));  //俱乐部成员人数
        if (uid != null) {
            clubBaseInfo.setJoin(clubMemberService.isClubMember(uid, tbClub.getId()));  //是否加入了俱乐部
        }
        TbClubActivityExample clubActivityExample = new TbClubActivityExample();
        clubActivityExample.createCriteria()
                .andIsDeleteEqualTo(Constants.BYTE_ZERO).andClubIdEqualTo(tbClub.getId());
        int count = clubActivityMapper.countByExample(clubActivityExample);
        clubBaseInfo.setHasActivity(count > 0 ? 1:0);
        clubBaseInfo.setChatgroupid(tbClub.getImGroupid());     //俱乐部聊天室id

        clubBaseInfo.setRealNameAuth(isRealNameAuthClub(tbClub.getId()));   //是否已经实名认证
        clubBaseInfo.setPurpose(tbClub.getPurpose());//俱乐部宗旨
        return clubBaseInfo;
    }

    /**
     * 俱乐部系统LOGO列表
     * @return
     */
    private List<TbClubSystemLogo> getClubSystemLogoList(){

        TbClubSystemLogoExample example = new TbClubSystemLogoExample();
        example.createCriteria()
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        example.setOrderByClause(" id desc");
        return this.clubSystemLogoMapper.selectByExample(example);
    }

    /**
     * 获取不同级别的俱乐部属性
     * @return
     */
    private List<TbClubProperty> getClubPropertyList(int parentId,int propertyLevel){
        TbClubPropertyExample example = new TbClubPropertyExample();
        TbClubPropertyExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andParentIdEqualTo(parentId);
        criteria.andPropertyLevelEqualTo((byte)propertyLevel);

        List<TbClubProperty> list = this.clubPropertyMapper.selectByExample(example);
        return list;
    }

    /**
     * 获取俱乐部积分排行榜
     * @param cityId            城市id
     * @param pageNo            页码
     * @param pageSize          每页记录数
     * @return
     */
    @Override
    public PageObj<List<RespClubBaseInfo>> getClubRankingList(Integer sportTypeId, Integer cityId, Integer pageNo, Integer pageSize) {
        int total = 0;
        TbClubExample example = new TbClubExample();
        TbClubExample.Criteria criteria = example.createCriteria();
        List<RespClubBaseInfo> rankingList = new ArrayList<>();
        Map<String, Object> paramMap = new HashMap<>();
        if (cityId != null && cityId != 0){
            criteria.andCityIdEqualTo(cityId);
            paramMap.put("cityId", cityId);
        }
        if (sportTypeId != null && sportTypeId != 0){
            criteria.andClubTypeEqualTo(sportTypeId);
            paramMap.put("sportTypeId", sportTypeId);
        }
        total = clubMapper.countByExample(example);
        //列表
        RowBounds rowBounds = new RowBounds((pageNo-1)*pageSize, pageSize);
        rankingList = sqlSessionTemplate.selectList("selectClubRankingList", paramMap, rowBounds);
        for (RespClubBaseInfo baseInfo : rankingList){
            baseInfo.setCity(getCity(baseInfo.getCityId()));
        }
        return PageObj.create(total, pageNo, pageSize, rankingList);
    }

    /**
     * 获取城市区域列表
     * @param cityId
     * @return
     */
    @Override
    public RespClubCity getCityDistrictList(int cityId) {
        RespClubCity respClubCity = new RespClubCity();
        respClubCity.setCityId(cityId);
        List<TbDistrict> districtList = super.getDistrictList(cityId);
        if (!districtList.isEmpty()) {
            List<RespClubDistrict> respClubDistrictList = new ArrayList<>();
            RespClubDistrict respClubDistrict;
            for (TbDistrict tbDistrict : districtList) {
                respClubDistrict = new RespClubDistrict();
                respClubDistrict.setDistrictId(tbDistrict.getId());
                respClubDistrict.setDistrictName(tbDistrict.getName());
                respClubDistrictList.add(respClubDistrict);
            }
            respClubCity.setRespDistrictList(respClubDistrictList);
        }
        return respClubCity;
    }

    /**
     * 获取俱乐部二维码
     * @param clubId
     * @return
     */
    @Override
    public RespClubQRCodeInfo getClubQRCode(int clubId) {
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        if(null == club){
            return null;
        }else{
            RespClubQRCodeInfo respClubQRCodeInfo = new RespClubQRCodeInfo();
            respClubQRCodeInfo.setClubId(clubId);
            respClubQRCodeInfo.setClubName(club.getClubName());
            respClubQRCodeInfo.setLogoUrl(club.getLogoUrl());

            RespClubBaseInfo respClubBaseInfo = new RespClubBaseInfo();
            respClubBaseInfo.setClubId(clubId);
            respClubBaseInfo.setClubName(club.getClubName());
            String json = GsonUtils.toJson(respClubBaseInfo);
            String param = Coder.encryptBASE64(json);
            StringBuffer sb = new StringBuffer();
            sb.append(clubShareUrl).append("?").append("clubId=").append(clubId);
//            sb.append("http://").append(quanyanBaseUrl).append("?source=bailingniaoqrcode&param=").append(param).append("&type=club");

            String httpResult = ShortUrlUtils.getShortUrl(sb.toString());

            StringBuffer shortUrl = new StringBuffer();
            if(httpResult != null){
                List<RespShareUrl> respShareUrls = JSON.parseArray(httpResult, RespShareUrl.class);
                shortUrl.append(respShareUrls.get(0).getUrl_short()).append("?source=bailingniaoqrcode&d=").append(clubId).append("&m=c");
            }
            respClubQRCodeInfo.setQRCodeUrl(shortUrl.toString());
            return respClubQRCodeInfo;
        }
    }

    /**
     * 获取已开通省列表
     * @param isLast
     * @return
     */
    private List<TbProvince> getEnableProvince(int isLast){
        TbProvinceExample example = new TbProvinceExample();
        TbProvinceExample.Criteria criteria = example.createCriteria();
        // 1 为已开通省市
        criteria.andIsEnableEqualTo(1);
        if(isLast == 0){
            example.setOrderByClause("id desc limit 0,1");
        }else{
            example.setOrderByClause("priority asc");
        }

        List<TbProvince> list = this.provinceMapper.selectByExample(example);
        return list;
    }

    /**
     * 更新俱乐部积分
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public void updateClubIntegral() {
        List<RespClubPartInfo> clubs = clubOpenExtendMapper.selectClubs();
        if (clubs.isEmpty()){
            return;
        }
        for (RespClubPartInfo club : clubs){
            Integer clubId = club.getId();
            List<TbClubMember> clubMembers = this.getClubMemberByClubId(clubId);
            if (clubMembers.isEmpty()){
                continue;
            }
            List<Integer> uids = new ArrayList<>();
            for (TbClubMember clubMember : clubMembers){
                uids.add(clubMember.getUid());
            }
            List<ResPoints> resPoints = stadiumOpenService.batchQueryUserCategoryPoints(uids,club.getClubType());
            if (!resPoints.isEmpty()){
                Integer integral = 0;
                for (ResPoints resPoint: resPoints){
                    integral += resPoint.getScore();
                }
                clubOpenExtendMapper.updateClubIntegral(clubId,integral);
                //更新索引
                RespClubBaseInfo clubBaseInfo = convert2RespClubBaseInfo(null, clubMapper.selectByPrimaryKey(clubId), false);
                clubBaseInfo.setGoingActivityCount(activitySupportService.countActivityAfterWeek(clubId));
                clubBaseInfo.setStar(clubIntegralService.updateSearchClubStar(clubId));
                executor.submit(new ClubSolrIndexThread(clubBaseInfo , clubSearchService, true));
            }
        }
    }

    /**
     * 获取俱乐部成员
     * @param clubId
     * @return
     */
    public List<TbClubMember> getClubMemberByClubId(Integer clubId){
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria().andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> clubMemberList = this.clubMemberMapper.selectByExample(example);
        return clubMemberList;
    }

    @Override
    public MqResponse test(String string) {
        /**************************通知mq，为该俱乐部添加经验***************************/
        //TODO
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        RespClubXpLevelMsg respClubXpLevelMsg = new RespClubXpLevelMsg();
        respClubXpLevelMsg.setClubId(164);
        respClubXpLevelMsg.setUid(154);
        // TODO
        respClubXpLevelMsg.setExpName("POST_ACTIVITY");
        mqRequestMsg.setMsgId(UUID.randomUUID().toString());
        mqRequestMsg.setTopic(MqConstants.CLUB_XP_LEVEL_TOPIC_NAME);
        mqRequestMsg.setFlag(0);
        mqRequestMsg.setTag(MqConstants.CLUB_XP_LEVEL_TAGS_NAME);
        mqRequestMsg.setBody(ObjectUtil.toByteArray(respClubXpLevelMsg));
        MqResponse mqResponse = this.clubXpLevelProducer.syncSend(mqRequestMsg);
        /**************************通知mq，为该俱乐部添加经验***************************/
        return mqResponse;
    }

    @Override
    public RespMyAllClubs listMyAllClubs(int uid) {
        RespMyAllClubs allClubs = new RespMyAllClubs();

        allClubs.setUid(uid);

        //我创建的
        TbClubExample tbClubExample = new TbClubExample();
        TbClubExample.Criteria criteria = tbClubExample.createCriteria();
        criteria.andUidEqualTo(uid)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        tbClubExample.setOrderByClause(" create_time desc");
        List<TbClub> mycreate = clubMapper.selectByExample(tbClubExample);
        List<RespClubBaseInfo> _mycreate = new ArrayList<>();
        if (mycreate != null){
            for (TbClub tbClub : mycreate){
                _mycreate.add(this.convert2RespClubBaseInfo(uid, tbClub, false));
            }
        }
        allClubs.setMyCreated(_mycreate);

        //我管理的
        TbClubMemberExample tbClubMemberExample = new TbClubMemberExample();
        tbClubMemberExample.createCriteria()
                .andUidEqualTo(uid)
                .andRoleCodeIn(Arrays.asList(Constants.ClubRole.ROLE_CLUB_FINANCIAL,
                        Constants.ClubRole.ROLE_CLUB_ADMIN))
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        tbClubMemberExample.setOrderByClause(" create_time desc");
        List<TbClubMember> mymanage = clubMemberMapper.selectByExample(tbClubMemberExample);
        List<RespClubBaseInfo> _mymanage = new ArrayList<>();
        if (mymanage != null){
            for (TbClubMember member : mymanage){
                TbClub tbClub = clubMapper.selectByPrimaryKey(member.getClubId());
                if (tbClub == null){
                    continue;
                }
                _mymanage.add(this.convert2RespClubBaseInfo(uid, tbClub, false));
            }
        }
        allClubs.setMyManage(_mymanage);

        //我加入的
        Map<String, Object> map = new HashMap<>();
        map.put("uid", uid);
        List<Integer> clubIds = sqlSessionTemplate.selectList("selectMyJoinedClubs", map);
        List<RespClubBaseInfo> _myjoined = new ArrayList<>();
        for (Integer clubId : clubIds){
            TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
            if (tbClub == null){
                continue;
            }
            if (mymanage != null) {
                boolean du = false;
                for (TbClubMember tbClubMember : mymanage) {
                    if (tbClubMember.getClubId().intValue() == clubId) {        //我管理里面的有，此处不显示
                        du = true;
                    }
                }
                if (du) {
                    continue;
                }
            }
            _myjoined.add(this.convert2RespClubBaseInfo(uid, tbClub, true));
        }
        allClubs.setMyJoined(_myjoined);

        return allClubs;
    }

    @Override
    public List<RespClubBaseInfo> getMyManageClubList(int uid) {
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andUidEqualTo(uid)
                .andRoleCodeIn(Arrays.asList(
                        Constants.ClubRole.CLUB_ROLE_PRESIDENT,
                        Constants.ClubRole.ROLE_CLUB_ADMIN,
                        Constants.ClubRole.ROLE_CLUB_FINANCIAL))
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbClubMember> tbClubMembers = clubMemberMapper.selectByExample(example);
        List<RespClubBaseInfo> resultList = new ArrayList<>();
        for (TbClubMember clubMember : tbClubMembers){
            TbClub tbClub = clubMapper.selectByPrimaryKey(clubMember.getClubId());
            if (tbClub.getIsDelete() == 1 || tbClub.getClubType() > 4){ //只要足篮网羽
                continue;
            }
            resultList.add(this.convert2RespClubBaseInfo(uid, tbClub, false));
        }

        return resultList;
    }

    @Autowired
    private TbSystemParametersMapper systemParametersMapper;

    @Override
    public String getClubFAQLink(int hrefNo) {

        String paramKey = null;
        switch (hrefNo){
            case 1:
                paramKey = "faq.settlement.activity";
                break;
            case 2:
                paramKey = "faq.finance.mgt";
                break;
            case 3:
                paramKey = "faq.star.rule";
                break;
            case 4:
                paramKey = "faq.order.detail";
                break;
            default:
                paramKey = "";
        }
        if (StringUtil.isBlankOrNull(paramKey)){
            return "";
        }

        TbSystemParametersExample example = new TbSystemParametersExample();
        example.createCriteria()
                .andParamKeyEqualTo(paramKey)
                .andIsEnableEqualTo(Constants.IS_YES);

        List<TbSystemParameters> parameterses = systemParametersMapper.selectByExample(example);
        if (parameterses != null && parameterses.size() != 0){
            return parameterses.get(0).getParamValue();
        }

        return null;
    }
}
